package com.zc.demo.xmlparser;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * Created by zhangchi9 on 2016/12/13.
 */
public class JdomParser implements XmlDocument{

    private String fileName;
    public JdomParser(){
        this.fileName = "D:\\jdom.xml";
    }
    @Override
    public void parseXml(String xml) {
        SAXBuilder builder = new SAXBuilder(false);
        try {
            Document document = builder.build(fileName);
            Element employees = document.getRootElement();
            List employeeList = employees.getChildren();
            // 获取employee节点
            for (int i = 0; i < employeeList.size(); i++) {
                Element employee = (Element) employeeList.get(i);
                List employeeInfo = employee.getChildren();
                // 获取employee节点下面的所有子节点
                for(int j = 0; j < employeeInfo.size(); j++) {
                    Element info = (Element)employeeInfo.get(j);
                    System.out.println(info.getName() + ":" + info.getValue());
                }
            }
        } catch (JDOMException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public String assembleXml() {
        Document document;
        Element root;
        root = new Element("employees");
        document = new Document(root);
        Element employee = new Element("employee");
        root.addContent(employee);
        Element name = new Element("name");
        name.setText("ddvip");
        employee.addContent(name);
        Element sex = new Element("sex");
        sex.setText("m");
        employee.addContent(sex);
        Element age = new Element("age");
        age.setText("23");
        employee.addContent(age);
        XMLOutputter XMLOut = new XMLOutputter();
        try {
            XMLOut.output(document, new FileOutputStream(fileName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
